//
//  FMPlayViewController.m
//  XWZ_News_Work
//
//  Created by dllo on 16/1/12.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "FMPlayViewController.h"
#import "FMPlayerHeadView.h"
#import "FMPlayTableViewCell.h"
#import "FMPlayModel.h"
#import "FMPlayVideoModel.h"
#import "FMTableViewModel.h"


@interface FMPlayViewController ()<UITableViewDelegate, UITableViewDataSource, FMPlayHeadViewDelegate>

@property (nonatomic, strong) UITableView *tableV;
@property (nonatomic, strong) FMPlayVideoModel *playModel;
@property (nonatomic, strong) NSMutableArray *arr;
@property (nonatomic, strong) UISlider *timeS;

@property (nonatomic, strong) FMPlayerHeadView *headV;
@property (nonatomic, strong) NSTimer *timerNext;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UILabel *labelT;
@property (nonatomic, strong) UILabel *labelM;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UIView *viewBG;
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIButton *buttonLast;
@property (nonatomic, strong) UIButton *buttonNext;
@property (nonatomic, strong) UIButton *buttonStop;


@end

@implementation FMPlayViewController

// 单例 全局
+ (instancetype)sharePlayerViewController
{
    static FMPlayViewController *player = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        player = [[FMPlayViewController alloc] init];
        
    });
    
    return player;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.indexNext = 0;
    self.indexLast = 0;
    self.page = 0;
    [self createView];
    
    
}

#pragma set
- (void)setDocid:(NSString *)docid
{
    if (_docid != docid) {
        _docid = docid;
        
    }
    
    [self getData];
    [self getDataList];
}

- (void)setTid:(NSString *)tid
{
    if (_tid != tid) {
        _tid = tid;
//        [self getData];
        [self getDataList];
        self.indexNext = 0;
        self.indexLast = 0;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"stop" object:nil];

    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    
    if (self.player.state == STKAudioPlayerStatePlaying) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:nil];
        
    } else {
    
        NSLog(@"6622222222");
    
    
    }
    
    
    
}

// 播放
- (void)CreatePlay
{
    [self.player stop];
    
        STKAudioPlayerOptions playerOption = {YES, YES, {50, 100 ,200, 400, 800, 1600, 2600, 16000}};
        
        self.player = [[STKAudioPlayer alloc] initWithOptions:playerOption];
        
        [self.player play:self.playModel.url_mp4];
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];

   
    
    

}

// 创建
- (void)createView
{
    [self createTableView];
    [self toolView];
}

// 滑动隐藏
- (void)toolView
{
    self.viewBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
//    self.viewBG.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.viewBG];
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button.frame = CGRectMake(5 * WIDTH, 18 * HEIGHT, 42 * WIDTH, 42 * HEIGHT);
    [self.button setImage:[UIImage imageNamed:@"huati-fanhui (1)"] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.viewBG addSubview:self.button];
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(self.button.frame.size.width + self.button.frame.origin.x, self.button.frame.origin.y, self.view.frame.size.width - (self.button.frame.size.width + self.button.frame.origin.x) - 10 * WIDTH, 42 * HEIGHT)];
    
    [self.viewBG addSubview:self.label];
    
    self.buttonStop = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonStop.frame = CGRectMake(self.viewBG.frame.size.width / 2 - 25 * WIDTH,  self.button.frame.origin.y + self.button.frame.size.height + 10 * HEIGHT, 50 * WIDTH, 50 * HEIGHT);
    //    [self.buttonStop setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    [self.buttonStop addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    [self.viewBG addSubview:self.buttonStop];
    
    
    self.buttonLast = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonLast.frame = CGRectMake(self.buttonStop.frame.origin.x - 80 * WIDTH, self.buttonStop.frame.origin.y, self.buttonStop.frame.size.width, self.buttonStop.frame.size.height);
    [self.buttonLast setImage:[UIImage imageNamed:@"iconfont-shangyishou-3"] forState:UIControlStateNormal];
    [self.buttonLast addTarget:self action:@selector(lastAction) forControlEvents:UIControlEventTouchUpInside];
    [self.viewBG addSubview:self.buttonLast];
    
    
    
    
    self.buttonNext = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonNext.frame = CGRectMake(self.buttonStop.frame.origin.x + self.buttonStop.frame.size.width + 30 * WIDTH, self.buttonStop.frame.origin.y, self.buttonStop.frame.size.width, self.buttonStop.frame.size.height);
    [self.buttonNext setImage:[UIImage imageNamed:@"iconfont-xiayishou-1"] forState:UIControlStateNormal];
    [self.buttonNext addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [self.viewBG addSubview:self.buttonNext];
    
    
}

// 创建头视图
- (void)createHeadView
{
    
    self.headV = [[FMPlayerHeadView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * 2 / 3)];
    self.headV.delegate = self;
    [self.headV.imageV sd_setImageWithURLStr:self.playModel.cover placeholderImage:[UIImage imageNamed:@"night_audio_block_bg"]];
        self.tableV.tableHeaderView = self.headV;
    
    self.timeS = [[UISlider alloc] initWithFrame:CGRectMake(60 * WIDTH, self.view.frame.size.width * 2 / 3 - 30 * HEIGHT, self.view.frame.size.width - 120 * WIDTH, 10 * HEIGHT)];
    [self.timeS addTarget:self action:@selector(timeAction) forControlEvents:UIControlEventValueChanged];
    
     [self.headV addSubview:self.timeS];
    
    self.labelM = [[UILabel alloc] initWithFrame:CGRectMake(5 * WIDTH, self.timeS.frame.origin.y - 20 * HEIGHT, 50 * WIDTH, 50 * HEIGHT)];

    self.labelM.font = [UIFont systemFontOfSize:13.0 * WIDTH];
    self.labelM.textColor = [UIColor whiteColor];
    self.labelM.textAlignment = NSTextAlignmentCenter;
    self.labelM.text = @"00:00";
    [self.headV addSubview:self.labelM];
    
    
    
    self.labelT = [[UILabel alloc] initWithFrame:CGRectMake(self.timeS.frame.origin.x + self.timeS.frame.size.width + 5 * WIDTH, self.labelM.frame.origin.y, self.labelM.frame.size.width, self.labelM.frame.size.height)];
    self.labelT.font = [UIFont systemFontOfSize:13.0 * WIDTH];
    self.labelT.textAlignment = NSTextAlignmentCenter;
    self.labelT.text = @"00:00";

    self.labelT.textColor = [UIColor whiteColor];
    [self.headV addSubview:self.labelT];
    
    
}



// 获取音乐数据
- (void)getData
{
    self.playModel = [[FMPlayVideoModel alloc] init];
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", self.docid];
 
    [xwzAFNetTool getNetWithURL:url body:nil headFile:nil responStyle:XWZ_JSON success:^(NSURLSessionDataTask *task, id responseObject) {
               NSMutableDictionary *dic = [responseObject objectForKey:self.docid];
        NSMutableArray *arr = [dic objectForKey:@"video"];
        NSMutableDictionary *tempDic = [arr objectAtIndex:0];
//        self.playModel = [[FMPlayVideoModel alloc] initWithDic:tempDic];
        [self.playModel setValuesForKeysWithDictionary:tempDic];
        [self createHeadView];
        [self CreatePlay];
        self.label.text = self.playModel.alt;
         [self.buttonStop setImage:[UIImage imageNamed:@"zantingbofang"] forState:UIControlStateNormal];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"数据解析失败");
    }];
}

// 获取播放界面列表数据
- (void)getDataList
{
    
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/%@/0-20.html", self.tid];
    [xwzAFNetTool getNetWithURL:url body:nil headFile:nil responStyle:XWZ_JSON success:^(NSURLSessionDataTask *task, id responseObject) {
        
       
        NSMutableArray *arr = [responseObject objectForKey:self.tid];
        self.arr = [NSMutableArray array];
        for (NSMutableDictionary *tempDic in arr) {
            FMTableViewModel *model = [[FMTableViewModel alloc] initWithDic:tempDic];
            [self.arr addObject:model];
        }
        
        
        [self.tableV reloadData];
       
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"数据请求失败");
        
    }];
}


// 上拉加载
- (void)getDataListUp
{
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/%@/%ld-20.html", self.tid, self.page];
    
    [xwzAFNetTool getNetWithURL:url body:nil headFile:nil responStyle:XWZ_JSON success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        NSMutableArray *arr = [responseObject objectForKey:self.tid];
        NSMutableArray *listArr = [NSMutableArray array];
        for (NSMutableDictionary *tempDic in arr) {
            FMTableViewModel *model = [[FMTableViewModel alloc] initWithDic:tempDic];
            [listArr addObject:model];
        }
        
        [self.arr addObjectsFromArray:listArr];
        [self.tableV reloadData];
        [self.tableV.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"数据请求失败");
        
    }];
}





// 创建创建tableview
- (void)createTableView
{
    self.tableV = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    [self.tableV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(@0);
        make.left.mas_equalTo(@0);
        make.width.equalTo(self.view.mas_width);
        make.height.equalTo(self.view.mas_height);
        
    }];
    
   
//    [self createUpToLoadData];
    
}

// 协议播放
- (void)playAction
{
    if (STKAudioPlayerStatePlaying == self.player.state) {
        [self.player pause];
        [self.headV.stop setImage:[UIImage imageNamed:@"audionews_play_button"] forState:UIControlStateNormal];
        [self.buttonStop setImage:[UIImage imageNamed:@"iconfont-zanting-2"] forState:UIControlStateNormal];
        self.headV.stop.selected = NO;
        
    } else if (STKAudioPlayerStatePaused == self.player.state) {
        [self.player resume];
        [self.headV.stop setImage:[UIImage imageNamed:@"audionews_pause_button"] forState:UIControlStateNormal];
        
        [self.buttonStop setImage:[UIImage imageNamed:@"zantingbofang"] forState:UIControlStateNormal];
        self.headV.stop.selected = YES;
        
        
    } else {

        [self.headV.stop setImage:[UIImage imageNamed:@"audionews_play_button"] forState:UIControlStateNormal];
        [self.buttonStop setImage:[UIImage imageNamed:@"iconfont-zanting-2"] forState:UIControlStateNormal];
        self.headV.stop.selected = NO;

        if (self.arr.count == self.indexNext) {
            self.indexNext = 0;
            self.indexLast = 0;
            self.docid = [[self.arr objectAtIndex:0] docid];
        }
        
        
    }
}


//timeAction
- (void)timeAction
{
//    [self.player seekToTime:self.timeS.value];

}
- (void)timerAction
{
    // 进度条的最大值
    self.timeS.maximumValue = self.player.duration;
   
    // 进度条更新
    self.timeS.value = self.player.progress;
    
    NSString *strMf = [NSString stringWithFormat:@"%ld", (NSInteger)self.player.progress / 60];
    NSString *strMm = [NSString stringWithFormat:@"%ld", (NSInteger)self.player.progress % 60];
    self.labelM.text = [NSString stringWithFormat:@"%@ : %@", strMf, strMm];
    self.labelT.text = [NSString stringWithFormat:@"%ld : %ld", (NSInteger)self.player.duration / 60, (NSInteger)self.player.duration % 60];
    
   // 自动下一首
// if (nil != self.playModel) {
//        if (STKAudioPlayerStateStopped == self.player.state) {
//            NSLog(@"333333");
//            [self.player stop];
//            [self.timer invalidate];
//            self.indexNext += 1;
//            self.indexLast += 1;
//           
//            [self.headV.stop setImage:[UIImage imageNamed:@"audionews_play_button"] forState:UIControlStateNormal];
//            if (self.indexNext < self.arr.count) {
//                NSLog(@"last = %ld  next = %ld", self.indexLast, self.indexNext);
//                self.docid = [[self.arr objectAtIndex:(NSInteger)self.indexNext] docid];
//            }
////
//            [self.headV.stop setImage:[UIImage imageNamed:@"audionews_play_button"] forState:UIControlStateNormal];
//            [self.buttonStop setImage:[UIImage imageNamed:@"iconfont-zanting-2"] forState:UIControlStateNormal];
//           
//        }
    
// } else {
// 
//     self.playModel = nil;
// 
// }
}


// 上一首
- (void)lastAction
{
    if (0 != self.arr.count) {
    
        if (0 < self.indexLast) {
            [self.player stop];
            [self.timer invalidate];
            self.indexLast -= 1;
            self.indexNext -= 1;
            NSLog(@"last = %ld  next = %ld", self.indexLast, self.indexNext);
            self.docid = [[self.arr objectAtIndex:self.indexLast] docid];
        }
        
    }
}
// 下一首
- (void)nextAction
{
    
    if (self.indexNext < self.arr.count - 1) {
    if (0 != self.arr.count) {
        [self.player stop];
        if (nil != self.playModel) {
            
                [self.player stop];
                [self.timer invalidate];
                self.indexNext += 1;
                self.indexLast += 1;
                NSLog(@"last = %ld  next = %ld", self.indexLast, self.indexNext);
                self.docid = [[self.arr objectAtIndex:(NSInteger)self.indexNext] docid];
            }
        }

    }

}






//tableview行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.arr.count;
}
// 自定义cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != self.indexNext) {
        static NSString *cellStr = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        if (nil == cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellStr];
        }
        cell.textLabel.text = [[self.arr objectAtIndex:indexPath.row] title];
        cell.detailTextLabel.text = [[self.arr objectAtIndex:indexPath.row] ptime];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14.0 * WIDTH];
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
       ;
        cell.backgroundColor = [UIColor colorWithRed:244.0 / 255.0 green:244.0 / 255.0 blue:244.0 / 255.0 alpha:1];
        return cell;
    } else {
    static NSString *cellPlay = @"cellP";
        
        FMPlayTableViewCell *cellP = [tableView dequeueReusableCellWithIdentifier:cellPlay];
        if (nil == cellP) {
            cellP = [[FMPlayTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellPlay];
        }
        
        cellP.labelTitle.text = [[self.arr objectAtIndex:indexPath.row] title];
        cellP.labelTitle.textColor = [UIColor redColor];
        cellP.detailTextLabel.font = [UIFont systemFontOfSize:14.0];
        cellP.detailTextLabel.text = [[self.arr objectAtIndex:indexPath.row] ptime];
               cellP.selectionStyle = UITableViewCellSelectionStyleBlue;
        cellP.imageV.image = [UIImage imageNamed:@"audionews_playlist_playing02"];

        return cellP;
    
    
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != self.indexLast) {
        return 80 * HEIGHT;
    } else {
    
        return 50 * HEIGHT;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.player stop];
    [self.timer invalidate];
    FMTableViewModel *model = [self.arr objectAtIndex:indexPath.row];
    self.docid = model.docid;
    // 上一曲
    self.indexLast = indexPath.row;
    self.indexNext = indexPath.row;
}

// 图片动画
- (void)imageViewAudio
{
    
}

// 上拉加载
- (void)createUpToLoadData
{
    self.tableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableV.mj_footer beginRefreshing];
}

// 上拉数据请求
- (void)loadMoreData
{
    self.page += 20;
    
    [self getDataListUp];
    
}

- (void)buttonAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 滑动显示隐藏toolview
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.viewBG.backgroundColor = [UIColor colorWithRed:1.0 green:0 blue:0 alpha:scrollView.contentOffset.y / 255.0 * HEIGHT];
    self.buttonNext.alpha = scrollView.contentOffset.y / 255.0 * HEIGHT;
    self.buttonStop.alpha = scrollView.contentOffset.y / 255.0 * HEIGHT;
    self.buttonLast.alpha = scrollView.contentOffset.y / 255.0 * HEIGHT;
    self.label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:scrollView.contentOffset.y / 255.0 * HEIGHT];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
